package cn.com.callback

import groovy.json.*;
import java.util.Map;
import java.text.ParseException
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import cn.com.elite.EliteBean;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONException;

import cn.com.elite.Util;
import cn.com.kh.getProperty;
import cn.com.kh.KHUtil;

/**
 *
 * @Title: autoDECaseList
 * @Description1: DE30015 同步案件基本信息（用于市属责任单位）同步案件的基本信息
 * @Description2: DE30004 同步案件附件信息 获取案件的附件信息
 * @Description3: DE30010 案件流程任务同步 获取案件的流程任务信息
 * @author: LiJuntao
 * @date 2020-05-15 下午1:14:48
 *
 */
public class autoDECaseList implements CallBackInvoke {
    private static final Log log = LogFactory.getLog(autoDECaseList.class);


    // DE30015 同步案件基本信息
    public void doCallBack(EliteBean eliteBean, String callBack, Map map, String paramString) {

        getCaseList(eliteBean);

        getCaseTasks(eliteBean);

    }

    // DE30015 同步案件基本信息
    public void getCaseList(EliteBean eliteBean) {

        String logPrefix = "DE30015 同步案件基本信息-";

        log.debug(logPrefix + "开始...");

        // 获取最后一次的同步时间
        String getUpdateTime = "Select TOP 1 DATEADD(hour, -1, Sync_Time) Sync_Time From SZWG_DE_Case_List Where Sync_Time > DATEADD(day, -7, GETDATE()) ORDER BY dbLastUpdateDate DESC";

        def sqlResult = eliteBean.chaxun_sql(getUpdateTime, "dataSource");

        def Sync_Time = null;
        if (sqlResult.size() > 0) {
            Sync_Time = sqlResult.get(0).get("Sync_Time");
        } else {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = new Date();
            Calendar rightNow = Calendar.getInstance();
            rightNow.setTime(date);
            rightNow.add(Calendar.DAY_OF_MONTH, -7);
            Date dt1 = rightNow.getTime();
            Sync_Time = formatter.format(dt1);
        }

        String requestId = UUID.randomUUID().toString();
        String time = String.valueOf(System.currentTimeMillis() / 1000L);

        // 设置头文件
        Map<String, String> headMap = new HashMap<String, String>();
        headMap.put("Content-Type", "application/json");
        headMap.put("funCode", "DE30015");
        headMap.put("appId", getProperty.get("DE.appId"));
        headMap.put("appKey", getProperty.get("DE.appKey"));
        headMap.put("requestId", requestId);
        headMap.put("timestamp", time);
        headMap.put("encoding", "");

        JSONObject callJson = new JSONObject();

        callJson.put("updateTime", Sync_Time);
        callJson.put("deptId", getProperty.get("DE.deptId"));

        log.debug(logPrefix + "调用地址URL：" + getProperty.get("DE.URL"));
        log.debug(logPrefix + "调用头文件信息:" + headMap.toString());
        log.debug(logPrefix + "调用发送报文信息：" + callJson.toString());
        String reJson = Util.doHttpPostUseHead(getProperty.get("DE.URL"), callJson.toString(), "UTF-8", 30000, 0, headMap);
        log.debug(logPrefix + "调用返回信息：" + reJson.toString());

        JSONObject inObject = new JSONObject(reJson);
        String errorCode = KHUtil.GetJV(inObject, "errorCode");
        String errorMsg = KHUtil.GetJV(inObject, "errorMsg");
        String data = KHUtil.GetJV(inObject, "data");

        if (errorCode.equals("0")) {

            long rstartTime = System.currentTimeMillis();
            long rendTime = System.currentTimeMillis();
            log.debug(logPrefix + "处理开始时间:" + rstartTime);

            try {
                JSONArray arrJsonArray = new JSONArray(data);

                int arrInt = arrJsonArray.length();
                log.debug(logPrefix + "接入List数量:" + arrInt);

                for (int i = 0; i < arrInt; i++) {

                    JSONObject arrCustJson = arrJsonArray.getJSONObject(i);

                    //解析案件信息
                    String evtId = KHUtil.GetJV(arrCustJson, "evtId");
                    String regTime = KHUtil.GetJV(arrCustJson, "regTime");
                    String endTime = KHUtil.GetJV(arrCustJson, "endTime");
                    String acceptId = KHUtil.GetJV(arrCustJson, "acceptId");
                    String code = KHUtil.GetJV(arrCustJson, "code");
                    String evtSrcId = KHUtil.GetJV(arrCustJson, "evtSrcId");
                    String typeId = KHUtil.GetJV(arrCustJson, "typeId");
                    String bigClassId = KHUtil.GetJV(arrCustJson, "bigClassId");
                    String smallClassId = KHUtil.GetJV(arrCustJson, "smallClassId");
                    String partCode = KHUtil.GetJV(arrCustJson, "partCode");
                    String title = KHUtil.GetJV(arrCustJson, "title");
                    String position = KHUtil.GetJV(arrCustJson, "position");
                    String eventDesc = KHUtil.GetJV(arrCustJson, "eventDesc");
                    String districtId = KHUtil.GetJV(arrCustJson, "districtId");
                    String streetId = KHUtil.GetJV(arrCustJson, "streetId");
                    String communityId = KHUtil.GetJV(arrCustJson, "communityId");
                    String workGridId = KHUtil.GetJV(arrCustJson, "workGridId");
                    String gridId = KHUtil.GetJV(arrCustJson, "gridId");
                    //String absX = KHUtil.GetJV(arrCustJson, "absX");
                    //String absY = KHUtil.GetJV(arrCustJson, "absY");
                    String absX = GetJV(arrCustJson, "absX");
                    String absY = GetJV(arrCustJson, "absY");
                    log.debug("absX:" + absX + ";absY" + absY);
                    String reporter = KHUtil.GetJV(arrCustJson, "reporter");
                    reporter = reporter.replaceAll("\'", "");
                    String replyWay = KHUtil.GetJV(arrCustJson, "replyWay");
                    String telNum = KHUtil.GetJV(arrCustJson, "telNum");
                    String status = KHUtil.GetJV(arrCustJson, "status");
                    String importantLevel = KHUtil.GetJV(arrCustJson, "importantLevel");
                    String dbCreateDate = KHUtil.GetJV(arrCustJson, "dbCreateDate");
                    String dbLastUpdateDate = KHUtil.GetJV(arrCustJson, "dbLastUpdateDate");
                    String dbLastUpdateId = KHUtil.GetJV(arrCustJson, "dbLastUpdateId");
                    String updateTime = KHUtil.GetJV(arrCustJson, "updateTime");
                    //判断，如果dbLastUpdateDate 为空，取updateTime
                    if (dbLastUpdateDate == null) {
                        dbLastUpdateDate = updateTime;
                    }


                    //查询现有当前案件是否存在
                    def getSelectSQL = eliteBean.chaxun_sql("Select top 1 dbLastUpdateDate,deal_result,fault_reason,color_flag From SZWG_DE_Case_List Where evtId = '" + evtId + "'", "dataSource");
                    log.debug("查询当前同步的工单是否已经存在 SQL:" + getSelectSQL + " 结果数量:" + getSelectSQL.size());

                    String oldLastUpdateDate = "";//最后更新时间
                    String color_flag = "";//工单状态对应不同颜色标识
                    //0红色底色（返单的案件） 1白色底色（未生成过投诉）、2淡蓝色底色（工单成功接收）、3深蓝色底色（工单未成功提交）、4绿色底色（有回复结果）
                    if (getSelectSQL.size() > 0) {
                        oldLastUpdateDate = getSelectSQL.get(0).get("dbLastUpdateDate");

                        color_flag = getSelectSQL.get(0).get("color_flag");
                    } else {
                        oldLastUpdateDate = "0";
                    }
                    def getHuiTuiSQL = eliteBean.chaxun_sql("SELECT top 1 evtId FROM SZWG_DE_Case_ReqReturn where 1=1 and (errorCode = '0' or errorMsg = '交易成功') and evtId = '" + evtId + "'", "dataSource");
                    if (getHuiTuiSQL.size() > 0) {
                        log.debug("getHuiTuiSQL:" + getHuiTuiSQL.get(0).get("evtId"));
                        color_flag = "0";
                        log.debug("getHuiTuiSQL返单案件");
                    } else {
                        def getJieAnSQL = eliteBean.chaxun_sql("SELECT top 1 evtId FROM SZWG_DE_Case_ReqComplete where 1=1 and (errorCode = '0' or errorMsg = '交易成功') and evtId = '" + evtId + "'", "dataSource");
                        if (getJieAnSQL.size() > 0) {
                            color_flag = "0";
                            log.debug("getJieAnSQL返单案件");
                        }
                    }


                    log.debug("oldLastUpdateDate: " + oldLastUpdateDate + "	,dbLastUpdateDate: " + dbLastUpdateDate);
                    // 插入数据
                    if (oldLastUpdateDate < dbLastUpdateDate) {
                        String[] batchSQL = new String[3];
                        batchSQL[0] = "Insert into SZWG_DE_Case_List_His select * from SZWG_DE_Case_List where evtId = '" + evtId + "'";
                        batchSQL[1] = "delete from SZWG_DE_Case_List where evtId = '" + evtId + "'";
                        batchSQL[2] = "INSERT INTO SZWG_DE_Case_List (evtId, regTime, endTime, acceptId, code, evtSrcId, typeId, bigClassId, smallClassId, partCode, title, position, eventDesc, districtId, streetId, communityId, workGridId, gridId, absX, absY, reporter, replyWay, telNum, status, importantLevel, dbCreateDate, dbLastUpdateDate, dbLastUpdateId, Sync_Time,deal_result,fault_reason,color_flag) VALUES ('" + evtId + "', '" + regTime + "', '" + endTime + "', '" + acceptId + "', '" + code + "', '" + evtSrcId + "', '" + typeId + "', '" + bigClassId + "', '" + smallClassId + "', '" + partCode + "', '" + title + "', '" + position + "', '" + eventDesc + "', '" + districtId + "', '" + streetId + "', '" + communityId + "', '" + workGridId + "', '" + gridId + "', '" + absX + "', '" + absY + "', '" + reporter + "', '" + replyWay + "', '" + telNum + "', '" + status + "', '" + importantLevel + "', '" + dbCreateDate + "', '" + dbLastUpdateDate + "', '" + dbLastUpdateId + "', getdate(), '', '', '" + color_flag + "')";

                        log.debug(logPrefix + "当前工单编号存在新建结果SQL:" + batchSQL.toString());
                        def dataresult = eliteBean.updateBatch(batchSQL, "dataSource");
                        log.debug(logPrefix + "当前工单编号存在新建结果SQL结果:" + dataresult.toString());
                    }

                    // 检查下载案件附件数据
                    getCaseAttachs(eliteBean, evtId, "4403");

                }

                //生成处理完成时间
                rendTime = System.currentTimeMillis();

                // 包装拼接返回JSONObject
                log.debug(logPrefix + "处理完成、调用问题处理时长(毫秒):" + (rendTime - rstartTime));

            } catch (JSONException e) {
                rendTime = System.currentTimeMillis();
                log.error(logPrefix + "处理失败(" + e.getMessage() + "),调用问题处理时长(毫秒):" + (rendTime - rstartTime));
            }

        }

    }

    // DE30010 案件流程任务同步
    public static boolean getCaseTasks(EliteBean eliteBean) {

        String logPrefix = "DE30010 案件流程任务同步-";

        log.debug(logPrefix + "开始...");

        // 获取最后一次的同步时间
        String getUpdateTime = "Select TOP 1 DATEADD(hour, -1, Sync_Time) Sync_Time From SZWG_DE_Case_Tasks Where Sync_Time > DATEADD(day, -7, GETDATE()) ORDER BY Sync_Time DESC";

        def sqlResult = eliteBean.chaxun_sql(getUpdateTime, "dataSource");

        def Sync_Time = null;
        if (sqlResult.size() > 0) {
            Sync_Time = sqlResult.get(0).get("Sync_Time");
        } else {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = new Date();
            Calendar rightNow = Calendar.getInstance();
            rightNow.setTime(date);
            rightNow.add(Calendar.DAY_OF_MONTH, -7);
            Date dt1 = rightNow.getTime();
            Sync_Time = formatter.format(dt1);
        }

        log.debug(logPrefix + "本次获取开始时间范围：" + Sync_Time);

        String requestId = UUID.randomUUID().toString();
        String time = String.valueOf(System.currentTimeMillis() / 1000L);

        //设置头文件
        Map<String, String> headMap = new HashMap<String, String>();
        headMap.put("Content-Type", "application/json");
        headMap.put("funCode", "DE30010");
        headMap.put("appId", getProperty.get("DE.appId"));
        headMap.put("appKey", getProperty.get("DE.appKey"));
        headMap.put("requestId", requestId);
        headMap.put("timestamp", time);
        headMap.put("encoding", "");

        JSONObject callJson = new JSONObject();
        callJson.put("deptId", getProperty.get("DE.deptId"));
        callJson.put("updateTime", Sync_Time);

        log.debug(logPrefix + "调用地址URL：" + getProperty.get("DE.URL"));
        log.debug(logPrefix + "调用头文件信息:" + headMap.toString());
        log.debug(logPrefix + "调用发送报文信息：" + callJson.toString());
        String reJson = Util.doHttpPostUseHead(getProperty.get("DE.URL"), callJson.toString(), "UTF-8", 10000, 0, headMap);
        log.debug(logPrefix + "调用返回信息：" + reJson.toString());
        long rstartTime = System.currentTimeMillis();
        long rendTime = System.currentTimeMillis();
        try {
            JSONObject inObject = new JSONObject(reJson);
            String errorCode = KHUtil.GetJV(inObject, "errorCode");
            String errorMsg = KHUtil.GetJV(inObject, "errorMsg");
            String data = KHUtil.GetJV(inObject, "data");

            if (errorCode.equals("0")) {
                log.debug(logPrefix + "处理开始时间:" + rstartTime);

                JSONArray arrJsonArray = new JSONArray(data);

                int arrInt = arrJsonArray.length();
                log.debug(logPrefix + "返回Array数量:" + arrInt);

                for (int i = 0; i < arrInt; i++) {

                    JSONObject arrCustJson = arrJsonArray.getJSONObject(i);

                    // Array信息解析
                    String id = KHUtil.GetJV(arrCustJson, "id");
                    String evtId = KHUtil.GetJV(arrCustJson, "evtId");
                    String inDate = KHUtil.GetJV(arrCustJson, "inDate");
                    String finishedDate = KHUtil.GetJV(arrCustJson, "finishedDate");
                    String limit = KHUtil.GetJV(arrCustJson, "limit");
                    String activityInstId = KHUtil.GetJV(arrCustJson, "activityInstId");
                    String remark = KHUtil.GetJV(arrCustJson, "remark");
                    String jumpType = KHUtil.GetJV(arrCustJson, "jumpType");

                    //查询现有当前案件任务是否存在
                    def getSelectSQL = eliteBean.chaxun_sql("Select top 1 id From SZWG_DE_Case_Tasks Where evtId = '" + evtId + "' and id = '" + id + "'", "dataSource");
                    log.debug("查询当前同步案件任务是否已经存在 SQL:" + getSelectSQL + " 结果数量:" + getSelectSQL.size());

                    if (getSelectSQL.size() > 0) {
                        String[] batchSQL = new String[3];
                        batchSQL[0] = "Insert into SZWG_DE_Case_Tasks_His select * from SZWG_DE_Case_Tasks where evtId = '" + evtId + "' and id = '" + id + "'";
                        batchSQL[1] = "delete from SZWG_DE_Case_Tasks where evtId = '" + evtId + "' and id = '" + id + "'";
                        batchSQL[2] = "INSERT INTO SZWG_DE_Case_Tasks (id, evtId, inDate, finishedDate, limit, activityInstId, remark,jumpType) VALUES ('" + id + "', '" + evtId + "', '" + inDate + "', '" + finishedDate + "', '" + limit + "', '" + activityInstId + "', '" + remark + "', '" + jumpType + "')";
                        log.debug(logPrefix + "查询现有任务编号已存在更新结果SQL:" + batchSQL.toString());
                        def dataresult = eliteBean.updateBatch(batchSQL, "dataSource");
                        log.warn(logPrefix + "查询现有任务编号已经存在更新结果SQL结果:" + dataresult.toString());
                    } else {
                        String[] batchSQL = new String[1];
                        batchSQL[0] = "INSERT INTO SZWG_DE_Case_Tasks (id, evtId, inDate, finishedDate, limit, activityInstId, remark,jumpType) VALUES ('" + id + "', '" + evtId + "', '" + inDate + "', '" + finishedDate + "', '" + limit + "', '" + activityInstId + "', '" + remark + "', '" + jumpType + "')";

                        log.debug(logPrefix + "查询现有任务编号不存在新建结果SQL:" + batchSQL.toString());
                        def dataresult = eliteBean.updateBatch(batchSQL, "dataSource");
                        log.debug(logPrefix + "查询现有任务编号不存在新建结果SQL结果:" + dataresult.toString());
                    }

                }

                //生成处理完成时间
                rendTime = System.currentTimeMillis();

                // 包装拼接返回JSONObject
                log.debug(logPrefix + "处理完成、调用问题处理时长(毫秒):" + (rendTime - rstartTime));

            }
        } catch (JSONException e) {
            rendTime = System.currentTimeMillis();
            log.error(logPrefix + "处理失败(" + e.getMessage() + "),调用问题处理时长(毫秒):" + (rendTime - rstartTime));
        }

    }

    // DE30004 同步案件附件信息
    public static boolean getCaseAttachs(EliteBean eliteBean, String evtIds, String areaCode) {

        String logPrefix = "DE30004 同步案件附件信息-";

        String requestId = UUID.randomUUID().toString();
        String time = String.valueOf(System.currentTimeMillis() / 1000L);

        //设置头文件
        Map<String, String> headMap = new HashMap<String, String>();
        headMap.put("Content-Type", "application/json");
        headMap.put("funCode", "DE30004");
        headMap.put("appId", getProperty.get("DE.appId"));
        headMap.put("appKey", getProperty.get("DE.appKey"));
        headMap.put("requestId", requestId);
        headMap.put("timestamp", time);
        headMap.put("encoding", "");

        JSONObject callJson = new JSONObject();
        JSONArray callArray = new JSONArray();
        callArray.put(evtIds);
        callJson.put("evtIds", callArray);
        callJson.put("areaCode", areaCode);

        log.debug(logPrefix + "调用地址URL：" + getProperty.get("DE.URL"));
        log.debug(logPrefix + "调用头文件信息:" + headMap.toString());
        log.debug(logPrefix + "调用发送报文信息：" + callJson.toString());
        String reJson = Util.doHttpPostUseHead(getProperty.get("DE.URL"), callJson.toString(), "UTF-8", 10000, 0, headMap);
        log.debug(logPrefix + "调用返回信息：" + reJson.toString());
        long rstartTime = System.currentTimeMillis();
        long rendTime = System.currentTimeMillis();
        try {
            JSONObject inObject = new JSONObject(reJson);
            String errorCode = KHUtil.GetJV(inObject, "errorCode");
            String errorMsg = KHUtil.GetJV(inObject, "errorMsg");
            String data = KHUtil.GetJV(inObject, "data");
            if (errorCode.equals("0")) {
                log.debug(logPrefix + "处理开始时间:" + rstartTime);
                JSONArray arrJsonArray = new JSONArray(data);

                int arrInt = arrJsonArray.length();
                log.debug(logPrefix + "返回Array数量:" + arrInt);

                for (int i = 0; i < arrInt; i++) {

                    JSONObject arrCustJson = arrJsonArray.getJSONObject(i);

                    // Array信息解析
                    String attachId = KHUtil.GetJV(arrCustJson, "attachId");
                    String evtId = KHUtil.GetJV(arrCustJson, "evtId");
                    String type = KHUtil.GetJV(arrCustJson, "type");
                    String usage = KHUtil.GetJV(arrCustJson, "usage");
                    String fileName = KHUtil.GetJV(arrCustJson, "fileName");
                    String CreateDate = KHUtil.GetJV(arrCustJson, "CreateDate");
                    String downUrl = KHUtil.GetJV(arrCustJson, "downUrl");

                    // 插入数据
                    def getSelectSQL = eliteBean.chaxun_sql("SELECT attachId from SZWG_DE_Case_Attachs where evtId = '" + evtId + "' and attachId = '" + attachId + "'", "dataSource");
                    log.debug("查询当前同步的工单是否已经存在 SQL:" + getSelectSQL + " 结果数量:" + getSelectSQL.size());

                    if (getSelectSQL.size() > 0) {
                        String[] batchSQL = new String[1];
                        batchSQL[0] = "update SZWG_DE_Case_Attachs set type = '" + type + "', usage = '" + usage + "', fileName = '" + fileName + "', CreateDate = '" + CreateDate + "', downUrl = '" + downUrl + "'where evtId = '" + evtId + "' and attachId = '" + attachId + "'";

                        log.debug(logPrefix + "现有附件编号已存在新建结果SQL:" + batchSQL.toString());
                        def dataresult = eliteBean.updateBatch(batchSQL, "dataSource");
                        log.debug(logPrefix + "现有附件编号已存在新建结果SQL结果:" + dataresult.toString());
                    } else {

                        String[] batchSQL = new String[1];
                        batchSQL[0] = "INSERT INTO SZWG_DE_Case_Attachs (attachId, evtId, type, usage, fileName, CreateDate, downUrl) VALUES ('" + attachId + "', '" + evtId + "', '" + type + "', '" + usage + "', '" + fileName + "', '" + CreateDate + "', '" + downUrl + "')";

                        log.debug(logPrefix + "现有附件编号不存在新建结果SQL:" + batchSQL.toString());
                        def dataresult = eliteBean.updateBatch(batchSQL, "dataSource");
                        log.debug(logPrefix + "现有附件编号不存在新建结果SQL结果:" + dataresult.toString());
                    }


                }

                //生成处理完成时间
                rendTime = System.currentTimeMillis();

                // 包装拼接返回JSONObject
                log.debug(logPrefix + "处理完成、调用问题处理时长(毫秒):" + (rendTime - rstartTime));
            }
        } catch (JSONException e) {
            rendTime = System.currentTimeMillis();
            log.error(logPrefix + "处理失败(" + e.getMessage() + "),调用问题处理时长(毫秒):" + (rendTime - rstartTime));
        }

    }

    public static String GetJV(JSONObject inJson, String getKey) {
        String Rev_Value = null;

        try {
            Rev_Value = inJson.getDouble(getKey);
        } catch (Exception e1) {

        } finally {
            if ((Rev_Value == null) || (Rev_Value.equals("null")) || (Rev_Value.length() <= 0)) {
                Rev_Value = "";
            }
        }
        return Rev_Value;
    }
}